﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32.TaskScheduler;

namespace SQLServerOptimizer.PL.WPF
{
    public class ScheduleTask
    {
        public void CreateTask(DateTime time, int type, int option, Int16 interval, List<DaysOfTheWeek> daysOfWeek , int dayOfMonth , WhichWeek weeksOfMonth , DaysOfTheWeek daysOfTheWeek , MonthsOfTheYear monthsOfTheYear )
        {

            using (TaskService ts = new TaskService())
            {
                   // Create a new task definition and assign properties
                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = "";

           
                if (type == 1)
                {
                    if (option == 1)
                    {
                        td.Triggers.Add(new DailyTrigger(interval)).StartBoundary = time;
                        
                    }
                    else
                    {
                        
                        foreach (var day in daysOfWeek)
                        {
                            td.Triggers.Add(new WeeklyTrigger(day, interval)).StartBoundary = time;
                        }

                    }

                }
                else if (type == 2)
                {
                    foreach (var day in daysOfWeek)
                    {
                        td.Triggers.Add(new WeeklyTrigger(day, interval)).StartBoundary = time;
                    }
                }
                else if (type == 3)
                {
                    if (option == 1)
                    {
                       
                        td.Triggers.Add(new MonthlyTrigger(dayOfMonth, monthsOfTheYear)).StartBoundary = time;
                    }
                    if (option == 2)
                    {
                        td.Triggers.Add(new MonthlyDOWTrigger(daysOfTheWeek, monthsOfTheYear, weeksOfMonth)).StartBoundary = time;
                    }

                }
                //// Create an action that will launch Notepad whenever the trigger fires
                td.Actions.Add(new ExecAction(System.Windows.Forms.Application.StartupPath + @"\SQLServerOptimizer.PL.WPF.exe", "ScheduledScan", null));

                       ts.RootFolder.RegisterTaskDefinition(@"SQLServerOptimizerScheduledScan", td);
             
            }
        }

        private void removetask(object sender, EventArgs e)
        {
            using (TaskService ts = new TaskService())
            {
                ts.RootFolder.DeleteTask("Test");
            }
        }
    }
}
